package com.kkb.mybatis.framework.handler;

import com.kkb.mybatis.framework.config.MappedStatement;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

public class DefaultResultSetHandler implements ResultSetHandler{
    @Override
    public List<Object> handleResultSet(ResultSet resultSet, PreparedStatement preparedStatement, MappedStatement mappedStatement) throws Exception {
        // 获取返回结果类型
        Class resultTypeClazz = mappedStatement.getResultTypeClass();

        // 构造器
        Constructor constructor = resultTypeClazz.getConstructor();
        List<Object> results = new ArrayList<>();
        Object result = null;
        while (resultSet.next()) {
            result = constructor.newInstance();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            for (int i = 0; i < columnCount; i++) {
                String columnName = metaData.getColumnName(i + 1);
                Field field = resultTypeClazz.getDeclaredField(columnName);
                field.setAccessible(true);
                field.set(result, resultSet.getObject(columnName));
            }
            results.add(result);
        }
        return results;
    }
}
